//
//  InputView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/8/22.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

//输入框类型
enum InputStyle {
    
    case account //账号
    case phone //手机号码
    case password //密码
    case code //验证码
}

@objc protocol TextDelegate {

    @objc optional func monitorText() //监听文本框
    @objc optional func getPhoneCode() //获取手机验证码
}

class InputView: UIView {
    
    weak var textDelegate : TextDelegate?
    
    var codeBlock : (([String:Any]) -> Void)? //发送验证码的回调
    
    var timer : Timer! //验证码计时器
    var sounds : Int = 0 //当前秒数
    
    let iconImageView = UIImageView() //图标
    let textField = UITextField() //输入框
    let lineView = UIView() // 底部黑线
    lazy var codeButton = UIButton() //验证码按钮
    
    //输入框文本
    var text : String {
        return textField.text!
    }
    
    //输入框水印文本
    var placeholder : String! {
        didSet{
            textField.placeholder = placeholder
        }
    }

    //MARK: 创建输入框
    init(inputStyle : InputStyle) {
        super.init(frame: .zero)
        
        textField.clearButtonMode = .always //输入框清除按钮
        textField.borderStyle = .none //隐藏边框
        textField.font = UIFont.systemFont(ofSize: RATIO(maxNum: 15))
        //注册输入框监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextChange(sender:)), name: .UITextFieldTextDidChange, object: textField)
        
        
        lineView.backgroundColor = UIColor.gray
        
        if inputStyle == .code {
            codeButton.setTitle(getCode, for: .normal)
            codeButton.setTitleColor(UIColor.black, for: .normal)
            codeButton.backgroundColor = UIColor.white
            codeButton.layer.cornerRadius = RATIO_H(maxNum: 15)
            codeButton.layer.masksToBounds = true
            codeButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 15))
            codeButton.addTarget(self, action: #selector(getCodeAction), for: .touchUpInside)
        }
        
        switch inputStyle {
        case .account:
            iconImageView.image = #imageLiteral(resourceName: "sign_user")
            textField.placeholder = inputAccount
            textField.keyboardType = .numberPad
        case .phone:
            iconImageView.image = #imageLiteral(resourceName: "sign_phone")
            textField.placeholder = inputPhone
            textField.keyboardType = .numberPad
        case .password:
            iconImageView.image = #imageLiteral(resourceName: "sign_lock")
            textField.placeholder = inputPassword
        case .code:
            iconImageView.image = #imageLiteral(resourceName: "sign_key")
            textField.placeholder = checkCode
            textField.keyboardType = .numberPad
            
        }
        
        makeConstraints(inputStyle: inputStyle)
    }
    
    //MARK: 设置约束
    fileprivate func makeConstraints(inputStyle : InputStyle) {
        
        self.addSubview(iconImageView)
        self.addSubview(textField)
        self.addSubview(lineView)
        
        iconImageView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(RATIO(maxNum: 30))
            make.width.height.equalTo(RATIO_H(30))
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(RATIO(maxNum: 20))
            make.right.equalToSuperview().offset(RATIO(maxNum: -20))
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        
        if inputStyle == .code {
        
            self.addSubview(codeButton)
            codeButton.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(RATIO(maxNum: -30))
                make.centerY.equalToSuperview()
                make.height.equalTo(RATIO_H(30))
                make.width.equalTo(100)
            }
            
            textField.snp.makeConstraints { (make) in
                make.left.equalTo(iconImageView.snp.right).offset(RATIO(maxNum: 20))
                make.centerY.equalToSuperview()
                make.height.equalTo(RATIO_H(30))
                make.right.equalTo(codeButton.snp.left).offset(RATIO(maxNum: -20))
            }
        }else{
            textField.snp.makeConstraints { (make) in
                make.left.equalTo(iconImageView.snp.right).offset(RATIO(maxNum: 20))
                make.centerY.equalToSuperview()
                make.right.equalToSuperview().offset(RATIO(maxNum: -20))
                make.height.equalTo(RATIO_H(30))
            }
        }
    }
    
    //MARK: 获取验证码
    @objc fileprivate func getCodeAction() {
        
        self.textDelegate?.getPhoneCode!()
        
        self.codeBlock = { (json) in
            
            KMTool.showText(_text: (json["msg"] as? String)!)
            
            //判断验证码是否发送成功 0表示成功
            if json["status"] as? String == "0" {
                
                self.codeButton.isEnabled = false
                self.sounds = 60
                self.codeButton.setTitle("\(self.sounds)", for: .normal)
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.waitforCode), userInfo: nil, repeats: true)
                
            }
        }
        
        
    }
    
    //MARK: 等待验证码
    @objc fileprivate func waitforCode() {
        
        sounds -= 1
        codeButton.setTitle("\(sounds)", for: .normal)
        
        if sounds == 1 {
            codeButton.setTitle(getCode, for: .normal)
            codeButton.isEnabled = true
            timer.invalidate()
            timer = nil
        }
    }
    
    //MARK: 监听文本
    @objc fileprivate func textFieldTextChange(sender : Notification) {
        
        self.textDelegate?.monitorText!()
        
    }
    
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}
